package com.example.administrator.printoutindemo;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dothantech.lpapi.IAtBitmap;
import com.dothantech.printer.IDzPrinter;
import com.example.administrator.printoutindemo.base.BaseActivity;
import com.example.administrator.printoutindemo.http.SPUtil;
import com.example.administrator.printoutindemo.zxing.activity.CaptureActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.utils.ToastUtil;
import com.xiaoxing.zhinenghuacangku.mvp.ui.utils.PrinterUtil;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.util.HashMap;

/**
 * Created by Administrator on 2019/3/9.
 */

public class SaomiaoActivity extends BaseActivity {

    LocationListener locationListener = new LocationListener() {

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {
        }

        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {

        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {

        }
    };
    private ImageView iv_qysaomiao;
    private String scanResult = "";
    private String lat = "";
    private String lng = "";
    private PrinterUtil mPrinterUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saomiao);
        mPrinterUtil = new PrinterUtil(this);
        IDzPrinter.Factory.getInstance().init(this, mPrinterUtil.mCallback);

        getLngAndLat(SaomiaoActivity.this);
        iv_qysaomiao = (ImageView) findViewById(R.id.iv_qysaomiao);
        iv_qysaomiao.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent openCameraIntent = new Intent(SaomiaoActivity.this,
                        CaptureActivity.class);
                startActivityForResult(openCameraIntent, 0);
            }
        });
    }

    private String getLngAndLat(Context context) {
//        double latitude = 0.0;
//        double longitude = 0.0;
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  //从gps获取经纬度
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return lat + "," + lng;
            }
            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (location != null) {
                lat = String.valueOf(location.getLatitude());
                lng = String.valueOf(location.getLongitude());
                Log.e("=================", lat + "======" + lng);
            } else {//当GPS信号弱没获取到位置的时候又从网络获取
                return getLngAndLatWithNetwork();
            }
        } else {    //从网络获取经纬度
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (location != null) {
                lat = String.valueOf(location.getLatitude());
                lng = String.valueOf(location.getLongitude());
            }
        }
        return lat + "," + lng;
    }

    public String getLngAndLatWithNetwork() {
//        double latitude = 0.0;
//        double longitude = 0.0;
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return lat + "," + lng;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null) {
            lat = String.valueOf(location.getLatitude());
            lng = String.valueOf(location.getLongitude());
        }
        return lat + "," + lng;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            scanResult = bundle.getString("result");
            if (scanResult != null | TextUtils.isEmpty(scanResult)) {
                HashMap<String, String> map = new HashMap<>();
                map.put("material_id", scanResult);
                map.put("monthid", SPUtil.getString(SaomiaoActivity.this, "qymid", ""));
                checkMaterialForSimpleGetter();
            }
        }
    }

    private void checkMaterialForSimpleGetter() {


        String methodName = "checkMaterialForSimpleGetter";

        SoapParams params = new SoapParams();
        params.put("material_id", scanResult);
        params.put("monthid", SPUtil.getString(SaomiaoActivity.this, "qymid", ""));
        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    Log.e("dayin=========", result);
                    if (result.equals("success")) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(SaomiaoActivity.this);
                        builder.setTitle("提示");
                        builder.setMessage("匹配成功! 请点击确定按钮打印二维码！");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                                HashMap<String, String> map1 = new HashMap<String, String>();
                                map1.put("monthid", SPUtil.getString(SaomiaoActivity.this, "qymid", ""));
                                map1.put("lng", lng);
                                map1.put("lat", lat);
                                createSimpleCodeSaveGPS();
                            }
                        });
                        builder.create().show();
                    } else {
                        ToastUtil.showMessage(SaomiaoActivity.this, "匹配失败！！！");
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void createSimpleCodeSaveGPS() {


        String methodName = "createSimpleCodeSaveGPS";

        SoapParams params = new SoapParams();
        params.put("monthid", SPUtil.getString(SaomiaoActivity.this, "qymid", ""));
        params.put("lng", lng);
        params.put("lat", lat);
        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    SPUtil.putString(SaomiaoActivity.this, "quyangerweima", result);
                    printQRcode(result);
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void printQRcode(String content) {
        if (mPrinterUtil.selectPrinterCheck()) {

            // 得到 IDzPrinter 对象
            IDzPrinter printer = IDzPrinter.Factory.getInstance();
            // 连接配对的第一个打印机对象
            printer.connect(IDzPrinter.Factory.getFirstPrinter());
            // 创建 IAtBitmap 绘图对象
            IAtBitmap api = IAtBitmap.Factory.createInstance();
            // 开始绘图任务，传入参数(页面宽度, 页面高度)
            api.startJob(48 * 100, 50 * 100);//48, 50
            // 开始一个页面的绘制，绘制二维码
            api.draw2DQRCode(content, 10 * 100, 5 * 100, 25 * 100);//  9, 10, 20,30
            api.drawText("封签码:", 0 * 100, 32 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);

            // 结束绘图任务
            api.endJob();
            // 打印
            printer.print(api, null);
        }
    }

}
